package com.test.interceptors;

import com.alibaba.fastjson.JSON;
import com.test.constants.Constant;
import com.test.pojo.TbUser;
import com.test.utils.ReturnResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    //当前请求线程
    private static ThreadLocal<TbUser> threadLocal=new ThreadLocal<>();

    private RedisTemplate<String,String> redisTemplate;

    public LoginInterceptor(RedisTemplate<String,String> redisTemplate){
        this.redisTemplate=redisTemplate;
    }
/*
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token==null || token.equals("")) {
            String s = JSON.toJSONString(ReturnResult.ERROR);
            response.getWriter().write(s);
            return false;
        }
        try {
            String json = redisTemplate.opsForValue().get(token);
            TbUser user = JSON.parseObject(json, TbUser.class);
            String key= Constant.REDIS_USER_KEY_PREFIX+user.getName();
            redisTemplate.opsForValue().set(key,json,1800, TimeUnit.SECONDS);
            threadLocal.set(user);
            return true;
        } catch (Exception e) {
            String s = JSON.toJSONString(ReturnResult.ERROR);
            response.getWriter().write(s);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }

    public static TbUser getUserInfo(){
        return threadLocal.get();
    }*/
}
